<template>
	<view>
		<view class="example">
			<!-- 基础表单校验 -->
			<uni-forms ref="valiForm" :rules="rules" :modelValue="FormData">
				<uni-forms-item label="名称" required name="name">
					<uni-easyinput v-model="FormData.name" placeholder="请输入名称" />
				</uni-forms-item>
				<uni-forms-item label="数量" required name="num">
					<uni-easyinput v-model="FormData.num" placeholder="请输入数量" />
				</uni-forms-item>
				<uni-forms-item label="备注" name="remark">
					<uni-easyinput type="textarea" v-model="FormData.remark" placeholder="请输入备注" />
				</uni-forms-item>
				<!-- <uni-forms-item label="图片" name="img">
					<uni-easyinput type="textarea" v-model="FormData.img" placeholder="请输入图片" />
				</uni-forms-item> -->
				<view class="text-area">
					<text class="title">{{title}}</text>
				</view>
				<uni-forms-item  name="img">
					<image class="logo" :src="FormData.img" @click="selectFile"></image>
				</uni-forms-item>
				
				<!-- <input v-model="FormData.img" disabled=""/> -->
			</uni-forms>
			<button type="primary" @click="submit('valiForm')">提交</button>
		</view>
	</view>
</template>

<script>
	import OSS from  '@/tools/ossTools/aliyun.js'
	export default {
		data() {
			return {
				title: '请选择上传的图片:',
				// 校验表单数据
				FormData: {
					name: '',
					num: '',
					remark: '',
					img: 'https://zc-oss1.oss-cn-hangzhou.aliyuncs.com/photo/2023-10/%E4%B8%8A%E4%BC%A0%E5%9B%BE.png'
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '名称不能为空'
						}]
					},
					num: {
						rules: [{
							required: true,
							errorMessage: '数量不能为空'
						}, {
							format: 'number',
							errorMessage: '数量只能输入数字'
						}]
					}
				},
				
			}
		},
		methods: {
			selectFile() {
					let that = this
					uni.chooseImage({
						count: 9, // 默认最多一次选择9张图
						sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
						
						success: function(res) {
							console.log(res)
							
							let tempFilePaths = res.tempFilePaths; //本地临时路径
							
							for(var i = 0; i < tempFilePaths.length; i++){
								if (res.tempFiles[i].size > OSS.uploadFileSize) { //OSS.uploadFileSize在aliyun.js里面设置，
									uni.showToast({
										title: '文件【'+ (i+1) +'】超过系统上传限制大小：' + OSS.uploadFileSize,
										icon: 'none',
										duration: 3000
									});
									return;
								}else{
									let date = new Date;
									let year = date.getFullYear();
									let month = date.getMonth() + 1;
									// 保存路径
									let filePath = "photo/" + year + "-" + month + "/" + Date.parse(new Date()) + parseInt(Math.random() * (100000 - 10000 + 1) + 10000, 10) + ".jpg" 
									
									// 调用上传函数
									that.fileUpload('picture', tempFilePaths[i], filePath);
								}							
								
							}
							
						}
					})
				},
				
			/* 上传函数 */ 
			fileUpload(type, path, stroeAs) {
				console.log('开始上传')
				// let self = this;
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: OSS.host,
						filePath: path,
						name: 'file',
						formData: {
							'key': stroeAs,
							'policy': OSS.policyBase64,
							'OSSAccessKeyId': OSS.accessid,
							'signature': OSS.signature,
							'success_action_status': '200'							
						},
						success: (res) => {
							console.log(res)
							uni.showToast({
								title: '上传成功',
								icon: 'success',
								duration: 1000
							});
							console.log(OSS.host + '/' + stroeAs)
							// this.FormData.img = '"' + OSS.host + '/' + stroeAs + '"';
							this.FormData.img = OSS.host + '/' + stroeAs;
							console.log(this.FormData.img )
							resolve('suc');
						},
						fail: (err) => {
							console.log('上传失败', err);
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
							reject('err')
						}
					})					
				})
			},
			submit(ref) {
			  this.$refs[ref].validate().then(res => {
			    console.log('success', res);
			    if (res) {
			      this.rukuDo(res); // 传递表单数据对象作为参数
			    } else {
			      console.log('表单验证失败');
			    }
			  }).catch(err => {
			    console.log('err', err);
			  });
			},
			// 事务
			transBegin(){
				plus.sqlite.transaction({
					name: 'CangKu',
					operation: 'begin',
					success: function(e){
						console.log('transaction begin success!');
					},
					fail: function(e){
						console.log('transaction begin failed: '+JSON.stringify(e));
					}
				});
			},
			transCommit(){
				plus.sqlite.transaction({
					name: 'CangKu',
					operation: 'commit',
					success: function(e){
						console.log('transaction commit success!');
					},
					fail: function(e){
						console.log('transaction commit failed: '+JSON.stringify(e));
					}
				});
			},
			// 表单存储
			rukuDo(FormData) {
			  // console.log("===表单数据=====",FormData.name,FormData.num,FormData.remark);			
			  const name = FormData.name;
			  const num = FormData.num;
			  const remark = FormData.remark;
			  const img = FormData.img;
			  this.transBegin();
			  const sql = `INSERT INTO goods (name, num, remark,img) VALUES ('${name}', '${num}', '${remark}','${img}')`;
			  console.log("-=---==-==数据展示",name,num,remark,img);
			  console.log("-=---==-==sql语句",sql);
			  plus.sqlite.executeSql({
			    name: 'CangKu',
			    sql: sql,
			    success: function(e) {
			      uni.showToast({
			        title: '提交成功 !',
			        icon: 'success'
			      });
			    },
			    fail: function(e) {
			      console.log('ruku failed: ' + JSON.stringify(e));
			    }
			  });
			  const sqlRecord = `INSERT INTO record (name, num, remark,type) VALUES ('${name}', '${num}', '${remark}','入库')`
			  plus.sqlite.executeSql({
			    name: 'CangKu',
			    sql: sqlRecord,
			    success: function(e) {
			      console.log('rukuRecord success');
			    },
			    fail: function(e) {
			      console.log('rukuRecord failed: ' + JSON.stringify(e));
			    }
			  });
			  this.transCommit()
			}

		}
	}
</script>

<style>
.example {
	padding: 15px;
	background-color: #fff;
}

</style>
